package com.android.lovely.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.android.lovely.databinding.ActivitySearchBinding
import com.android.lovely.ext.fullScreen
import com.android.lovely.framework.BaseMvvmActivity
import com.android.lovely.ui.fragment.SearchRecommendFragment
import com.android.lovely.ui.fragment.SearchResultFragment
import com.android.lovely.ui.viewmodel.SearchViewModel
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.keyboard.hideKeyboard
import com.kotlin.extensions.keyboard.showKeyboard
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest

/**
 *
 * @author why
 * @date 2025/3/13 11:10
 */
class SearchActivity : BaseMvvmActivity<ActivitySearchBinding, SearchViewModel>() {
    override fun initView(savedInstanceState: Bundle?) {
        fullScreen()
        mBinding.clTop.addStatusBarMarginTop()
        mBinding.ivBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        mBinding.ivClear.clickable {
            mBinding.etSearch.text?.clear()
        }
        mBinding.etSearch.addTextChangedListener {
            if (it.isNullOrEmpty()) {
                mBinding.ivSearch.isSelected = false
                mBinding.ivClear.visibility = android.view.View.GONE
            } else {
                mBinding.ivSearch.isSelected = true
                mBinding.ivClear.visibility = android.view.View.VISIBLE
            }
        }
        mBinding.etSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER &&
                        event.action == KeyEvent.ACTION_DOWN)
            ) {
                if (mBinding.etSearch.text.toString().isNotEmpty()) {
                    viewModel.search(mBinding.etSearch.text.toString())
                    mBinding.etSearch.clearFocus()
                    hideKeyboard()
                }
            }
            false
        }

        initRecommend()

        mBinding.ivSearch.clickable {
            if (mBinding.etSearch.text.toString().isEmpty()) return@clickable
            viewModel.search(mBinding.etSearch.text.toString())
            mBinding.etSearch.clearFocus()
            hideKeyboard()
        }
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (mBinding.flContainerResult.isVisible) {
                    mBinding.flContainerResult.visibility = View.GONE
                    requestFocus()
                    return
                }
                finish()
            }
        })
        lifecycleScope.launchSafety {
            viewModel.resultFlow.collectLatest {
                if (it) {
                    mBinding.etSearch.clearFocus()
                    mBinding.etSearch.setText(viewModel.searchKey)
                    initResult()
                    mBinding.flContainerResult.visibility = View.VISIBLE
                    hideKeyboard()
                } else {
                    mBinding.flContainerResult.visibility = View.GONE
                }
            }
        }

        val result = intent.getStringExtra("Result")
        if(result.isNullOrEmpty()) {
            requestFocus()
        } else {
            viewModel.search("#${result}")
            mBinding.etSearch.clearFocus()
            hideKeyboard()
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val result = intent.getStringExtra("Result")
        if(!result.isNullOrEmpty()) {
            viewModel.search("#${result}")
            mBinding.etSearch.clearFocus()
            hideKeyboard()
        }
    }

    private fun initRecommend() {
        // 创建一个 Fragment 实例
        val fragment = SearchRecommendFragment()
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(mBinding.flContainerRecommend.id, fragment)
        fragmentTransaction.commitNowAllowingStateLoss()
    }

    private fun initResult() {

        if(!isFinishing && !isDestroyed && supportFragmentManager.findFragmentByTag("result") != null){
            return
        }
        // 创建一个 Fragment 实例
        val fragment = SearchResultFragment()
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(mBinding.flContainerResult.id, fragment, "result")
        fragmentTransaction.commitNowAllowingStateLoss()
    }

    private fun requestFocus() {
        mBinding.etSearch.requestFocus()
        mBinding.etSearch.setSelection(mBinding.etSearch.text.length)
        showKeyboard()
    }
}